const DB = require('../../../../utils/db')
const JwtUtil = require('../../../../utils/jwt')
/**
 * GET, 参数friendid
 * 添加好友
 */

module.exports = async (ctx) => {
  // 获取token
  let token = ctx.request.header.authorization
  let jwt = new JwtUtil(token)
  // 用token获取到userid
  let userid = jwt.verifyToken()
  const hasFriend = await DB.query(
    `select * from user_friend where (userid='${userid}' and friendid='${ctx.request.query.friendid}') or (userid='${ctx.request.query.friendid}' and friendid='${userid}')`
  )
  if (hasFriend.length===2){
      ctx.body = {
        code: 0,
        data: '已经是好友啦',
      }
  }else{
    // const res = await DB.query(
    //   `insert user_friend(userid, friendid, friendStatus, createTime) VALUES('${userid}', '${ctx.request.query.friendid}', 0, now()),('${ctx.request.query.friendid}', '${userid}', 0, now());`
    // )
 

    // 查询申请信息
    const applyres = await DB.query(
      `select applyStatus from user_apply where applicantid='${userid}' and respondentid='${ctx.request.query.friendid}'`
    )
    console.log(applyres.length, 'applyres38')
    // 如果已经申请过
    if (applyres.length > 0 && applyres[0].applyStatus===0) {
          ctx.body = {
            code: 0,
            data: applyres,
          }

    } else {
      // 没有申请过,插入申请信息
      const res = await DB.query(
        `insert user_apply(applicantid,respondentid,applyStatus) values('${userid}','${ctx.request.query.friendid}',0)`
      )
          const applyres = await DB.query(
            `select applyStatus from user_apply where applicantid='${userid}' and respondentid='${ctx.request.query.friendid}'`
          )
         ctx.body = {
           code: 0,
           data: applyres,
         }
    }
  
  }

}
